import React, { useState } from 'react';
import { Card, Input, Button, List, Typography, Space, Alert, Tag, Spin, message } from 'antd';
import { LinkOutlined, CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { parseMagnetLink, downloadMagnetLink } from '../services/magnetService';
import { MagnetInfo } from '../types/magnet';

const { Title, Text } = Typography;

const MagnetParser: React.FC = () => {
    const [magnetLink, setMagnetLink] = useState('');
    const [parsedInfo, setParsedInfo] = useState<MagnetInfo | null>(null);
    const [error, setError] = useState('');
    const [copied, setCopied] = useState(false);
    const [loading, setLoading] = useState(false);
    const [downloadingIndex, setDownloadingIndex] = useState<number | null>(null);

    // 文件大小格式化函数
    const formatFileSize = (bytes: number): string => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
    };

    const handleParse = async () => {
        setError('');
        setParsedInfo(null);

        if (!magnetLink.trim()) {
            setError('请输入磁力链接');
            return;
        }

        try {
            setLoading(true);
            const info = await parseMagnetLink(magnetLink);
            if (info.status) {
                let magnetInfo: MagnetInfo = {
                    infoHash: info.name,
                    displayName: info.name,
                    fileCount: info.fileList.length,
                    totalSize: info.fileList.length,
                    files: info.fileList
                }
                setParsedInfo(magnetInfo);
            } else {
                setError('解析失败，重新点击解析');
            }

        } catch (err) {
            setError(err instanceof Error ? err.message : '解析磁力链接失败，请检查链接格式是否正确');
        } finally {
            setLoading(false);
        }
    };

    const handleCopy = (text: string) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        });
    };

    return (
        <Card title={<Title level={2}>磁力链接解析工具</Title>} variant="outlined" style={{ maxWidth: 800, margin: '0 auto' }}>
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <Space.Compact style={{ width: '100%' }}>
                    <Input
                        placeholder="请输入磁力链接"
                        value={magnetLink}
                        onChange={(e) => setMagnetLink(e.target.value)}
                        onPressEnter={handleParse}
                        prefix={<LinkOutlined />}
                        style={{ flex: 1 }}
                    />
                    <Button type="primary" onClick={handleParse} loading={loading}>解析</Button>
                </Space.Compact>

                {error && <Alert message="解析错误" description={error} type="error" showIcon />}

                {parsedInfo && (
                    <div>
                        <Title level={4}>解析结果</Title>
                        <List
                            bordered
                            dataSource={[
                                { label: 'Info Hash', value: parsedInfo.infoHash, copyable: true },
                                { label: '显示名称', value: parsedInfo.displayName || '未提供' },
                                { label: '文件数量', value: parsedInfo.fileCount?.toString() || '未知' },
                                { label: '总大小', value: parsedInfo.totalSize ? `${(parsedInfo.totalSize / (1024 * 1024)).toFixed(2)} MB` : '未知' },
                            ]}
                            renderItem={(item) => (
                                <List.Item
                                    actions={item.copyable ? [
                                        <Button
                                            icon={<CopyOutlined />}
                                            size="small"
                                            onClick={() => item.value && handleCopy(item.value)}
                                            type={copied ? 'primary' : 'default'}
                                        >
                                            {copied ? '已复制' : '复制'}
                                        </Button>
                                    ] : []}
                                >
                                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                                        <Text strong>{item.label}:</Text>
                                        <Text>{item.value}</Text>
                                    </div>
                                </List.Item>
                            )}
                        />

                        {loading ? (
                            <div style={{ textAlign: 'center', padding: '40px 0' }}>
                                <Spin size="large" tip="正在解析磁力链接..." />
                            </div>
                        ) : (
                            <>{
                                parsedInfo.files && parsedInfo.files.length > 0 ? (
                                    <div style={{ marginTop: 16 }}>
                                        <Title level={4}>文件列表</Title>
                                        <List
                                            bordered
                                            dataSource={parsedInfo.files}
                                            renderItem={(file, index) => (
                                                <List.Item key={index}>
                                                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}>
                                                        <Text>{file.fileName}</Text>
                                                        <Space>
                                                            <Text type="secondary">{formatFileSize(file.fileSize)}</Text>
                                                            <Button
                                                                icon={<DownloadOutlined />}
                                                                size="small"
                                                                onClick={() => {
                                                                    setDownloadingIndex(index);
                                                                    downloadMagnetLink(magnetLink, index)
                                                                        .then(() => message.success('下载已开始'))
                                                                        .catch(() => message.error('下载失败'))
                                                                        .finally(() => setDownloadingIndex(null));
                                                                }}
                                                                loading={downloadingIndex === index}
                                                            />
                                                        </Space>
                                                    </div>
                                                </List.Item>
                                            )}
                                        />
                                    </div>
                                ) : parsedInfo.fileCount && parsedInfo.fileCount > 1 ? (
                                    <Alert message="提示" description="无法获取详细文件列表，请尝试使用其他磁力链接或稍后再试" type="info" showIcon style={{ marginTop: 16 }} />
                                ) : null
                            }</>
                        )}

                        {parsedInfo.trackers && parsedInfo.trackers.length > 0 && (
                            <div style={{ marginTop: 16 }}>
                                <Title level={4}>Tracker 列表</Title>
                                <Space wrap>
                                    {parsedInfo.trackers.map((tracker, index) => (
                                        <Tag key={index} color="blue" style={{ margin: 4 }}>{tracker}</Tag>
                                    ))}
                                </Space>
                            </div>
                        )}
                    </div>
                )}
            </Space>
        </Card>
    );
};

export default MagnetParser;